<template>
  <div class="main1"
       v-loading="loading"
       element-loading-text="获取数据中……"
       element-loading-spinner="el-icon-loading">
    <div class="resultTitle">
      <p>关于<span>{{ $route.query.keyWord }}</span>的搜索, 共有<span>{{total}}</span>条结果:</p>
    </div>
    <div class="searchHome">
      <div class="result" v-if="resultList.length <= 0">
        <el-empty description="搜索结果为空"></el-empty>
      </div>
      <div class="items" v-else>
<!-- 注意异步问题 所以判断resultList是否为空 -->
        <div class="item" v-if="resultList" v-for="item in resultList" :key="item.id">
          <SingleNotice :notice="item"></SingleNotice>
        </div>
      </div>
    </div>
    <div class="pages">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="8"
        :total="total"
        :current-page="pageNum"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import SingleNotice from '../components/SingleNotice'
import qs from 'qs'
export default {
  name: 'SearchResult',
  components: {
    SingleNotice
  },
  data () {
    return {
      keyWord: '',
      resultList: [],
      total: 0,
      pageNum: 1,
      loading: false
    }
  },
  created () {
    this.keyWord = this.$route.query.keyWord;
    this.getData(0,8);
  },
  methods:{
    //请求数据库数据的方法
    getData(offset,limit){
      this.loading = true
      this.axios.post('/php/search.php', qs.stringify({
        offset: offset,
        limit: limit,
        keyWord: this.keyWord
      }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then((res) => {
        if(res.data === 0){
          this.total = 0
          this.resultList = []//清空上一次搜索结果
          this.loading = false;
          return;
        }
        this.total = res.data.total
        this.resultList = res.data.data
        this.loading = false
      }).catch((err) => {
        this.loading = false
        this.$message.error(err)
      })
    },
    handleCurrentChange(val){
      this.resultList = [];
      this.getData((val-1)*8,(val-1)*8+8);
    }
  },
  watch: {//因为是同一路由 所以要检测参数的改变 然后刷新数据
    $route(to, from) {
      if (this.$route.query.keyWord) {
        this.keyWord = this.$route.query.keyWord;
        this.getData(0,8);
      }
    }
  },

}
</script>

<style scoped>
.main1{
  margin-top: 60px;
}
.searchHome{
  display: flex;
  justify-content: center;
  padding: 0.5rem;
}
</style>
